package com.njtoyo.taxi.admin.logic.business;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.njtoyo.taxi.admin.library.qiniu.QiNiuService;
import com.njtoyo.taxi.admin.mapper.master.entity.DialRecord;
import com.njtoyo.taxi.admin.mapper.master.mapper.DialRecordMapper;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

@Service
@Slf4j
public class PrivacyNumberLogic {

    @Autowired
    private QiNiuService qiNiuService;

    @Autowired
    private DialRecordMapper dialRecordMapper;

    @Value("${config.qiniu.buckets.dialAudio.domain}")
    private String domain;

    @Value("${config.qiniu.buckets.dialAudio.bucket}")
    private String bucket;

    @Async
    public void downloadFileSave(DialRecord record) {
        String qiniuUrl = record.getQiniuUrl();
        if (Objects.nonNull(qiniuUrl)) {
            log.info("文件已保存到七牛");
        } else {
            byte[] downloadBytes = HttpUtil.downloadBytes(record.getHuaweiUrl());

            Configuration config = new Configuration();
            Auth auth = qiNiuService.auth();
            String uploadToken = auth.uploadToken(bucket);
            UploadManager uploadManager = new UploadManager(config);
            String filename = UUID.randomUUID().toString() + ".mp4";
            try {
                uploadManager.put(downloadBytes, filename, uploadToken);
                new LambdaUpdateChainWrapper<>(dialRecordMapper)
                        .eq(DialRecord::getId, record.getId())
                        .set(DialRecord::getQiniuUrl, domain + "/" + filename)
                        .set(DialRecord::getUpdatedAt, new Date())
                        .update();
                log.info("上传文件成功");
            } catch (Exception e) {
                log.info("上传文件错误 {}", e.getMessage());
            }
        }
    }
}
